package com.dycong.common.IO.netty.frame_coder;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * Created by dycong on 2017/3/13.
 */
public class EchoClient {

    private final String host;
    private final int port;
    private static final int MAX_FRAME_LENGTH = 1024 * 1024;
    private static final int LENGTH_FIELD_LENGTH = 4;
    private static final int LENGTH_FIELD_OFFSET = 2;
    public EchoClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void start() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .handler(new ChannelInitializer<SocketChannel>() {    //5当建立一个连接和一个新的通道时，创建到 EchoClientHandler 实例添加到 channel pipeline +


                        @Override
                        public void initChannel(SocketChannel ch)
                                throws Exception {
                            ch.pipeline().addLast(new MyLengthFieldBasedFrameDecoder(MAX_FRAME_LENGTH,LENGTH_FIELD_OFFSET,LENGTH_FIELD_LENGTH))
                                    .addLast(new MyMessageToByteEncoder())
                            .addLast(clientHandler);
                        }
                    });
            ChannelFuture f =  b.connect(new InetSocketAddress(host, port)).sync();

            f.channel().closeFuture().sync();

        } finally {
            group.shutdownGracefully().sync();
        }
    }

    static EchoClientHandler clientHandler = new EchoClientHandler();

    public static void main(String[] args) throws Exception {


        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    new EchoClient("localhost", 9090).start();
                }catch (Exception e){

                }
            }
        }).start();
        Scanner scanner = new Scanner(System.in);
        while (clientHandler.sendMsg(scanner.nextLine()));
         ;
    }
}
